<template>
    <div class="tinymce-box">
        <editor
            v-model="myValue"
            :init="init"
            :disabled="disabled"
            @onClick="onClick"
        >
        </editor>
    </div>
</template>
<script>
import axios from 'axios'

import tinymce from "tinymce"
//主题
import "tinymce/themes/silver"
import Editor from "@tinymce/tinymce-vue"
// 5.3.x图标显示not found的解决办法
import 'tinymce/icons/default/icons'

// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/plugins/image' // 插入上传图片插件
import 'tinymce/plugins/media' // 插入视频插件
import 'tinymce/plugins/table' // 插入表格插件
import 'tinymce/plugins/lists' // 列表插件
import 'tinymce/plugins/wordcount' // 字数统计插件
export default {
    components: {
        Editor
    },
    name: 'tinymce',
    props: {
        height: {
            type: Number,
            default: 300
        },
        value: {
            type: String,
            default: ''
        },
        disabled: {
            type: Boolean,
            default: false
        },
        plugins: {
            type: [String, Array],
            default: 'lists image media table wordcount'
        },
        toolbar: {
            type: [String, Array],
            default: 'undo redo |  formatselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | removeformat'
        }
    },
    data() {
        return {
            init: {
                // 静态资源目录，生产和开发不一样
                language_url: '/tinymce/langs/zh_CN.js',
                language: 'zh_CN',
                skin_url: '/tinymce/skins/ui/oxide',
                content_css: '/tinymce/skins/content/default/content.css',
                height: this.height,
                plugins: this.plugins,
                toolbar: this.toolbar,
                branding: false,
                menubar: false,
                images_upload_handler: (blobInfo, success, failure) => {
                    this.imgUpload(blobInfo, success, failure);
                },
                // 自定义按钮
                setup: (editor) => {
                    editor.ui.registry.addButton('imageUpload', {
                        tooltip: '插入图片',
                        icon: 'image',
                        onAction: () => {
                            this.app.chooseImage((data) => {
                                // 插入到编辑器中
                                data.forEach(item => {
                                    editor.insertContent(`&nbsp;<img src="${item.url}">&nbsp;`)
                                })
                            }, 100)
                        }
                    })
                }
            },

            qiniu: {
                token: '',
                prefix: '',
                upload_url: 'http://up-z2.qiniup.com'
            },
            myValue: this.value
        }
    },
    mounted() {
        tinymce.init({})
        this.getQiniuToken()
    },
    methods: {
        // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
        // 需要什么事件可以自己增加
        onClick(e) {
            this.$emit('onClick', e, tinymce)
        },
        // 可以添加一些自己的自定义事件，如清空内容
        clear() {
            // this.myValue = ''
        },
        getQiniuToken() {
            let url = 'admin/common/upload/qiniu/token'
            this.$ajax.post(url)
                .then(res => {
                    let data = res.data
                    if (!data.error_code) {
                        this.qiniu.token = data.data.token

                        this.qiniu.prefix = data.data.qiniu_url_prefix
                    } else {
                        this.$Message.error(data.message);
                    }

                }).catch(err => {
                    console.log(err)
                })
        },
        imgUpload(blobInfo, success, failure) {
            //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
            const axiosInstance = axios.create({ withCredentials: false });

            let data = new FormData();
            //七牛需要的token，叫后台给，是七牛账号密码等组成的hash
            data.append("token", this.qiniu.token);
            data.append("file", blobInfo.blob());

            axiosInstance({
                    method: "POST",
                    url: this.qiniu.upload_url, //上传地址
                    data: data,
                    timeout: 30000, //超时时间，因为图片上传有可能需要很久
                    onUploadProgress: progressEvent => {
                        //imgLoadPercent 是上传进度，可以用来添加进度条
                        let imgLoadPercent = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        );
                    }
                })
                .then(data => {
                    // 调用成功回调，返回用七牛外链地址和返回的key拼接的图片路径
                    success(`${this.qiniu.prefix}/${data.data.key}`);
                })
                .catch(function(err) {
                    //上传失败
                    console.log(err)
                });
        }
    },
    watch: {
        value(newValue) {
            this.myValue = newValue
        },
        myValue(newValue) {
            this.$emit('input', newValue)
        }
    }
}
</script>
<style scoped>
</style>